package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 统一校验用户身份的全局过滤器
 *
 * @Author mr.wu
 * @Date 2025-8-23 12:01
 */
@EnableConfigurationProperties({AuthProperties.class})
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private JwtTool jwtTool;

    /**
     * 过滤处理逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求实例和响应实例
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2. 获取请求路径（相对路径）
        String path = request.getURI().getPath();

        //3. 判断路径是否可放行
        //3.1 获取配置文件中所有可放行的路径
        List<String> excludePaths = authProperties.getExcludePaths();
        //统计出需要放行的路径个数
        long needPassCount = excludePaths.stream().filter(x -> antPathMatcher.match(x, path)).count();
        if(needPassCount>0) {
            return chain.filter(exchange);//放行请求
        }

        //4. 获取请求头中的令牌
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        //5. 令牌如果为空，则响应401
        if(StrUtil.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//做出响应
        }

        //6. 解析令牌
        try {
            Long userId = jwtTool.parseToken(token);

            //放行前设置用户ID到请求头中（期望将用户信息传递到目标微服务）
            request.mutate().header("user-info",userId.toString());

            //7. 解析成功，直接放行请求
            return chain.filter(exchange);

        } catch (Exception e) {
            e.printStackTrace();
            //8. 解析失败，则响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//做出响应
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
